package com.xdtech.wx.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.common.utils.JsonUtil;
import com.xdtech.sys.aspect.SystemControllerLog;
import com.xdtech.web.controller.BaseController;
import com.xdtech.web.model.ResultMessage;
import com.xdtech.wx.model.WxZklyInfo;
import com.xdtech.wx.service.WxZklyInfoService;
import com.xdtech.wx.util.WeixinUtil2;
import com.xdtech.wx.vo.WxPzswSolveItem;
import com.xdtech.wx.vo.WxZklyDayItem;
import com.xdtech.wx.vo.WxZklyInfoItem;
import com.xdtech.wx.vo.WxZklyTeamItem;
@Controller
//@Scope("session")
//@Scope("prototype")
public class ZklyAction extends BaseController{
	@Autowired
	private WxZklyInfoService wxZklyInfoService;
	@RequestMapping(value="/indexZkly.action")
	public ModelAndView indexZkly(HttpServletRequest request) {
		getWxConfigSign(request);
		String uuid = UUID.randomUUID().toString();
		request.setAttribute("uuid", uuid);
		return new ModelAndView("wx/zkly/index_ftl");
	}
	@RequestMapping(value="/indexZkly2.action")
	public ModelAndView indexZkly2(HttpServletRequest request) {
		getWxConfigSign(request);
		String uuid = UUID.randomUUID().toString();
		request.setAttribute("uuid", uuid);
		Map<String, Object> mapInfo = (Map<String, Object>) ApplicationContextUtil.getApplication().getAttribute("teamMapList");
		List<WxZklyTeamItem> teams = (List<WxZklyTeamItem>) mapInfo.get("all");
		request.setAttribute("teams", teams);
		String curPage = request.getParameter("curPage");
		request.setAttribute("curPage", StringUtils.isBlank(curPage)?0:curPage);
		return new ModelAndView("wx/zkly2/index_ftl");
	}
	@RequestMapping(value="/indexZkly2.action",params="detail")
	public ModelAndView detail(HttpServletRequest request,String teamId) {
		getWxConfigSign(request);
		String uuid = UUID.randomUUID().toString();
		request.setAttribute("uuid", uuid);
		Map<String, Object> mapInfo = (Map<String, Object>) ApplicationContextUtil.getApplication().getAttribute("teamMapList");
		WxZklyTeamItem team = (WxZklyTeamItem) mapInfo.get(teamId);
		request.setAttribute("team", team);
		List<WxZklyDayItem> dayItems = team.getDayItems();
		List<WxZklyDayItem> otherDays = new ArrayList<WxZklyDayItem>();
		for (WxZklyDayItem wxZklyDayItem : dayItems) {
			if (wxZklyDayItem.getDayTime().equals(DateUtil.dateToString(new Date(), DateStyle.YYYY_MM_DD))) {
				//今日销量
				request.setAttribute("today", wxZklyDayItem);
			}else {
				otherDays.add(wxZklyDayItem);
			}
		}
		request.setAttribute("otherdays", otherDays);
		
		return new ModelAndView("wx/zkly2/detail_ftl");
	}
	protected void getWxConfigSign(HttpServletRequest request) {
		Map<String,Object>  ret = new HashMap<String,Object> ();
        ret= WeixinUtil2.getWxConfig(request);
        request.setAttribute("appId", ret.get("appId"));
        request.setAttribute("timestamp", ret.get("timestamp"));
        request.setAttribute("nonceStr", ret.get("nonceStr"));
        request.setAttribute("signature", ret.get("signature"));
	}
	@ResponseBody
	@RequestMapping(value = "zkly.action",params = "upload")
	public String uploadFile(HttpServletRequest request,
			@RequestParam("filedata") MultipartFile file) throws Exception {
		List<String> filePathList = new ArrayList<String>();
		ResultMessage rs = new ResultMessage();
		try {
			String rootUrl = ApplicationContextUtil.getWebappUrl();
			String filePath = "zklYUploadFile/"+DateUtil.dateToString(new Date(), DateStyle.YYYYMMDD);
			String uploadDir = request.getRealPath("/"+filePath);
			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			int indexFile = file.getOriginalFilename().lastIndexOf(".");
			String fileName = System.currentTimeMillis()+"_"+RandomStringUtils.random(4, "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")+file.getOriginalFilename().substring(indexFile, file.getOriginalFilename().length());
//			System.out.println(file.getContentType());
			String imgUrl = filePath+"/"+fileName;
			filePath = uploadDir + "/"+fileName;
			file.transferTo(new File(filePath));
//			filePathList.add(imgUrl);
			rs.setObj(imgUrl);

		} catch (IOException e) {
			log.error("upload error",e);
			rs.setFailMsg("上传失败");
		}
		return JsonUtil.getJsonStr(rs);
	}
	
	@RequestMapping(value="/zkly.action",params = "bm")
	@ResponseBody
	public ResultMessage bm(WxZklyInfoItem item) {
		ResultMessage r = new ResultMessage();
		WxZklyInfo wxZklyInfo = wxZklyInfoService.getZklyInfoByUUID(item.getUuid());
		if (wxZklyInfo!=null) {
			r.setFailMsg("请勿重复报名");
		} else {
			if (wxZklyInfoService.saveOrUpdateWxZklyInfo(item)) {
				r.setSuccess(true);
			}else {
				r.setSuccess(false);
			}
		}
		
		return r;
	}
}
